/**
 * $Id$
 */
package ua.org.energy.vkek.site.web;

import com.google.gson.Gson;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import ua.org.energy.vkek.site.model.ArticleTag;
import ua.org.energy.vkek.site.server.DataIOException;
import ua.org.energy.vkek.site.server.EMF;
import ua.org.energy.vkek.site.server.TagUtils;

public class TagJsonServlet extends BaseJsonServlet {

    @Override
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/javascript;charset=UTF-8");
        //    throw new ServletException("test exception");
        ArticleTag tag;

        PrintWriter out = response.getWriter();

        String action = request.getParameter("action");
        if (checkParamValue(action)) {
            if (action.equalsIgnoreCase("ins")) {
                tag = attachToCategory(request.getParameter("selcategory"), request.getParameter("newtag"));
                printOk("insert", tag, out);
            } else if (action.equalsIgnoreCase("upd")) {
                tag = updateName(request.getParameter("seltag"), request.getParameter("newtag"));
                printOk("update", tag, out);
            } else if (action.equalsIgnoreCase("del")) {
                delete(request.getParameter("seltag"));//удаляем выбранный
                printOk("delete", null, out);
            } else {
                throw new ServletException("an unknown action");
            }
        } else {
            String category = request.getParameter("selcategory");
            if (checkParamValue(category)) {
                printTagListForCategory(category, out);
            } else {
                printTagList(out);
            }
        }
        out.close();
    }

    /**
     * выводит в out JSON объект - результат uid-операции над ArticleTag
     *
     * @param operation - тип операции - одна из строк 'insert', 'update',
     * 'delete'
     * @param ArticleCategory - категория - результат операции
     * вставки/обновления/для удаления(null)
     * @param out вывод для JSON
     */
    private void printOk(String operation, ArticleTag tag, PrintWriter out) {
        EntityUIDJson<ArticleTag> uidjson = new EntityUIDJson<ArticleTag>(operation, tag);
        printOk(uidjson, out);
    }

    private void printTagList(PrintWriter out) {
        List<ArticleTag> list = getListAll();
        printEntList(list, out);
    }

    private void printTagListForCategory(String category, PrintWriter out) {
        List<ArticleTag> list = getTagListForCategory(category);
        printEntList(list, out);
    }

    private List<ArticleTag> getListAll() {
        TagUtils utils = new TagUtils(EMF.getEM());
        return utils.listAll();
    }

    private List<ArticleTag> getTagListForCategory(String category) {
        TagUtils utils = new TagUtils(EMF.getEM());
        return utils.listForCategory(category);
    }

    /*
     * для UID операций транзакцию открывает EMFFilter
     */
    private ArticleTag attachToCategory(String categoryName, String tagName) throws DataIOException {
        if (checkParamValue(tagName)
                && checkParamValue(categoryName)) {
            TagUtils utils = new TagUtils(EMF.getEM());
            ArticleTag result = utils.attachToCategory(categoryName, tagName);
            EMF.safeCommit(EMF.getEM());
            return result;
        } else {
            throw new DataIOException("empty Tag name  while update");
        }
    }

    private ArticleTag updateName(String oldtagName, String newtagName) throws DataIOException {
        if (checkParamValue(newtagName)
                && checkParamValue(oldtagName)) {
            TagUtils utils = new TagUtils(EMF.getEM());
            ArticleTag result = utils.updateName(oldtagName, newtagName);
            EMF.safeCommit(EMF.getEM());
            return result;
        } else {
            throw new DataIOException("empty Tag name  while update");
        }
    }

    private void delete(String deltagName) throws DataIOException {
        if (checkParamValue(deltagName)) {
            TagUtils utils = new TagUtils(EMF.getEM());
            utils.delete(deltagName);
            EMF.safeCommit(EMF.getEM());
        } else {
            throw new DataIOException("empty Tag name  while delete");
        }

    }
}
